<?php
 /**
 * @author: Nguyen.Le 
 */
Yii::import('application.extensions.image.Image');
class ProfileService extends ServiceBase
{
 	 protected static function getCurrentUserAvatarFolder($userId)
 	 {
	 	// Each user has a private folder. Create it if it does not have
     	$folderPath = Yii::app()->getBasePath() . Yii::app()->Params['uploadFolder'] . $userId;
     	return ($folderPath . Yii::app()->Params['avatarFolder']);
 	 }
 	 
 	 protected static function uploadAvatar($userProfile, $avatarFolderPath, $fileId, $currentAvatar)
 	 {
	 	$result = $currentAvatar;
	 	Yii::import('application.extensions.helpers.CUploadedFile');
     	// Save upload file
     	$fAvatar = CUploadedFile::getInstance($userProfile, $fileId);
     	
     	// Return current avatar if no file is uploaded
     	if (is_null($fAvatar)) { return $result; }
     	
     	// Delete current avatar first
     	if (!empty($currentAvatar))
     	{
			$avatarFile = $avatarFolderPath . "/{$currentAvatar}";
			// If this file exists, just delete this file, not delete folder
			if (file_exists($avatarFile)) 
			{ 
				unlink($avatarFile);
			}
     	}
     	
     	// Create unique name for upload file
     	$fileName = com_create_guid() . '.' . $fAvatar->getExtensionName();

     	// Save to avatar folder first
     	$avatarFilePath =  $avatarFolderPath . "/{$fileName}";
     	if ($fAvatar->saveAs($avatarFilePath))
     	{
			$result = $fileName;
			
			// Resize thumb image
			$image  = new Image($avatarFilePath);
			$image->resize(Yii::app()->Params['avatarWidth'], Yii::app()->Params['avatarHeight']);
			$image->save();
     	} else {
			self::$result->ReturnCode = ServiceResult::RETURN_FAILURE;
			self::$result->ErrorMessages = "Cannot upload $fileId";
     	}
     	 
        return $result;
 	 }
 	 
	 public static function update($params)
	 {
		$userProfile = new UserProfile();
		self::getModel($params, $userProfile, 'editProfile');
		                                                
		if (self::$result->isFailed()) { return self::$result; }

		// Each user has a private folder. Create it if it does not have
		$userId = $userProfile->UserId;
		$avatarFolderPath = self::getCurrentUserAvatarFolder($userId);
		// Create avatar folder if it is not existed
		if (!file_exists($avatarFolderPath)) {
			mkdir($avatarFolderPath, 0700, true);
		}
		
		// Get current profile data in db
		$currentProfile = UserProfile::model()->find("UserId = {$userId}");

		// Update new avatar 1
		$avatar1 = self::uploadAvatar($userProfile, $avatarFolderPath, 'Avatar1', $currentProfile->Avatar1);
		if (self::$result->ReturnCode == ServiceResult::RETURN_SUCCESS) { 
			// Update new avatar 2
			$avatar2 = self::uploadAvatar($userProfile, $avatarFolderPath, 'Avatar2', $currentProfile->Avatar2);
			if (self::$result->ReturnCode == ServiceResult::RETURN_SUCCESS) { 
				// Update new avatar 3
				$avatar3 = self::uploadAvatar($userProfile, $avatarFolderPath, 'Avatar3', $currentProfile->Avatar3);
				
				// Update data to db
				$updatedFields = array('UserId' => $userId, 
        								'Gender' => $userProfile->Gender,
				                        'Nationality' => $userProfile->Nationality,
				                        'MaritalStatus' => $userProfile->MaritalStatus,
				                        'Birthday' => date('Y-m-d', strtotime($userProfile->Birthday)),
				                        'Address1' => $userProfile->Address1,
				                        'Address2' => $userProfile->Address2,
				                        'SocialId' => $userProfile->SocialId,
				                        'Phone' => $userProfile->Phone,
				                        'Mobile' => $userProfile->Mobile,
				                        'YIM' => $userProfile->YIM,
				                        'GoogleIM' => $userProfile->GoogleIM,
				                        'Skype' => $userProfile->Skype,
				                        'Avatar1' => $avatar1,
				                        'Avatar2' => $avatar2,
				                        'Avatar3' => $avatar3);

				// If this is a new profile
				$actionResult = ($userProfile->Id > 0) ? $userProfile->updateByPk($userProfile->Id, $updatedFields) : $userProfile->save();
				// Error message when action is failed
				if (!$actionResult)
				{
					self::$result->ReturnCode = ServiceResult::RETURN_FAILURE;
					self::$result->ErrorMessages = $userProfile->getErrors();
					Yii::app()->Session['ErrorMessage'] = self::$result->ErrorMessages;
				} else {
					// Redirect to edit profile page if success
					$url = Yii::app()->controller->createCmsUrl('edit-profile'); 
					Yii::app()->controller->redirect($url);
				}
			}		
		}
		
		return self::$result;	 
	 }
	 
	public static function deleteAvatar($params)
	{
		$result = true;
		try
		{
			$avatarId = self::getParam($params, 'fId', 1);
			$userId = Yii::app()->user->Id;
			// Get avatar file path
			$avatarFolderPath = self::getCurrentUserAvatarFolder($userId);
			$avatarField = "Avatar{$avatarId}";
			$userProfile = UserProfile::model()->find("UserId = {$userId}");
			$avatarFile = $avatarFolderPath . "/{$userProfile->$avatarField}";

			// If this file exists, just delete this file, not delete folder
			if (file_exists($avatarFile)) 
			{ 
				unlink($avatarFile);
			}

			// Update db
			$updatedField = array($avatarField => '');
			$result = UserProfile::model()->updateByPk($userProfile->Id, $updatedField);
		}
		catch (CException $ex)
		{
			Yii::log($ex->getMessage(), CLogger::LEVEL_ERROR);
			$result = false;
		}
		
		// Redirect to edit profile page if success
		if ($result) {
			$url = Yii::app()->controller->createCmsUrl('edit-profile'); 
			Yii::app()->controller->redirect($url);
		} else {
			self::$result->ReturnCode = ServiceResult::RETURN_FAILURE;
			self::$result->ErrorMessages = $userProfile->getErrors();	
			Yii::app()->Session['ErrorMessage'] = self::$result->ErrorMessages;
		}
		 
		return self::$result;
	}
}
?>
